package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 预编译SQL
 * 当SQL中含有变量时，通常我们不能直接拼接Sql语句
 */
public class JDBCDemo7 {
    public static void main(String[] args) {
        try (
                Connection connection = DBUtil.getConnection();
        ){
            String sql = "SELECT id,username,password,nickname,age " +
                    "FROM userinfo " +
                    "WHERE username=? " +
                    "AND password=?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,"aaa");
            preparedStatement.setString(2,"aaa' OR '1'='1");
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()){
                String nickname = resultSet.getString("nickname");
                System.out.println("登录成功"+","+nickname+"欢迎回来！");
            }else {
                System.out.println("登录失败！用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
